package com.llxz.blog.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.llxz.blog.basic.exceptionhandler.MyException;
import com.llxz.blog.ucenter.client.DeleteArticleById;
import com.llxz.blog.ucenter.entity.Provice;
import com.llxz.blog.ucenter.entity.User;
import com.llxz.blog.ucenter.entity.vo.ChangePasswordForm;
import com.llxz.blog.ucenter.entity.vo.RegisterForm;
import com.llxz.blog.ucenter.mapper.UserMapper;
import com.llxz.blog.ucenter.service.UserService;
import com.llxz.blog.util.IpUtil;
import com.llxz.blog.util.JwtUtils;
import com.llxz.blog.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

/**
 * Created by IntelliJ IDEA.
 *
 * @author lyq
 * @description: date: 2021/9/4 15:19
 */

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    DeleteArticleById deleteArticleById;

    @Autowired
    RedisTemplate<String,String> redisTemplate;





    @Override
    public String login(User user) {
        //获取手机号和密码
        String mobile = user.getMobile();
        String password = user.getPassword();
        //判断非空
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)){
            throw new MyException(2001,"有空值");
        }

        //是否已被注册
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",mobile);
        User temp = userMapper.selectOne(wrapper);
        if (temp == null||!MD5Utils.encrypt(password).equals(temp.getPassword())){
            throw new MyException(2001,"用户名或密码错误");
        }

        if (temp.getIsDeleted())
            throw new MyException(2001,"已注销");

        //登录成功
        String jwtToken = JwtUtils.createJwtToken(temp.getId(),temp.getName());

        addUserStatus(temp);
        //解析Ip
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        System.out.println("IP:"+request.getHeader("x-forwarded-for"));
        String provice = IpUtil.getAddressResult("113.140.84.102");
//        int num=userMapper.getProvicenum(provice);
//        System.out.println("省份数据:"+ num);
        Integer res = userMapper.updateProvicenum(provice);
        return jwtToken;
    }

    private void addUserStatus(User temp) {
        if (temp == null) {
            return;
        }
        Integer status = temp.getStatus();
        if (status == null) {
            status = 0;
        }
        temp.setStatus(status + 1);
        userMapper.updateById(temp);

    }

    @Override
    public void register(RegisterForm registerForm) {
        String name = registerForm.getName();
        String mobile = registerForm.getMobile();
        String password = registerForm.getPassword();
        String code = registerForm.getCode();
        System.out.println(code + "==============");

        //非空判断
        if(StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(code) || StringUtils.isEmpty(name)) {
            throw new MyException(2001,"注册信息填写完整");
        }

        //判断验证码
        //获取redis验证码
        String redisCode = redisTemplate.opsForValue().get(mobile);
        if(!code.equals(redisCode)) {
            throw new MyException(2001,"验证码输入错误");
        }

        //判断手机号是否重复，表里面存在相同手机号不进行添加
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",mobile);
        Integer count = userMapper.selectCount(wrapper);
        if(count > 0) {
            throw new MyException(2001,"该号码已注册");
        }

        //数据添加数据库中

        User user = new User();
        user.setMobile(mobile);
        user.setName(name);
        user.setPassword(MD5Utils.encrypt(password));//密码需要加密的
        user.setIsDeleted(false);//用户不禁用
        user.setIsDisable(false);
        user.setAvatar("https://online-edu-zzm.oss-cn-beijing.aliyuncs.com/cat.jpeg");
        user.setAvatar("http://www.baidu.com");
        userMapper.insert(user);
    }

    @Override
    public void changePassword(ChangePasswordForm changePasswordForm) {
        String code = changePasswordForm.getCode();
        String mobile = changePasswordForm.getMobile();
        String oldPassword = changePasswordForm.getOldPassword();
        String newPassword = changePasswordForm.getNewPassword();
        System.out.println(oldPassword);
        System.out.println(mobile + "////" + newPassword);

        //非空判断
//        if(StringUtils.isEmpty(mobile) || StringUtils.isEmpty(newPassword)
//                || StringUtils.isEmpty(code)) {
//            throw new MyException(2001,"信息不全");
//        }
        if(StringUtils.isEmpty(mobile) || StringUtils.isEmpty(newPassword) ){
            throw new MyException(2001,"信息不全");
        }
        //判断验证码
        //获取redis验证码
//        String redisCode = redisTemplate.opsForValue().get(mobile);
//        if(!code.equals(redisCode)) {
//            throw new MyException(2001,"注册码失效");
//        }
        //是否已被注册
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",mobile);
        User user = userMapper.selectOne(wrapper);
        if(Objects.isNull(user)){
            throw new MyException(2001,"用户不存在");
        }
        if(user.getPassword().equals(MD5Utils.encrypt(oldPassword))){
            //数据添加数据库中
            user.setPassword(MD5Utils.encrypt(newPassword));//密码需要加密的
            userMapper.updateById(user);
        }
        else{
            throw new MyException(2001,"原密码错误");
        }
    }
    @Override
    public void delete(String mobile, String password) {
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)){
            throw new MyException(2001,"信息不全");
        }

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",mobile).eq("password",MD5Utils.encrypt(password));

        User tmp = userMapper.selectOne(wrapper);

        if (null == tmp)
            throw new MyException(2001,"信息错误");
        tmp.setIsDeleted(true);
        userMapper.updateById(tmp);
    }
    //按天统计注册人数
    @Override
    public Integer countRegisterDay(String day) {
        return userMapper.countRegisterDay(day);
    }

    @Override
    public int countTotalRegister() {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("is_deleted",0);
        final Integer integer = userMapper.selectCount(wrapper);
        return integer;
    }

    @Override
    public int countOnlineNum() {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.ge("status",1);
        Integer num = userMapper.selectCount(wrapper);
        System.out.println(num + "service ========");
        return num;
    }

    @Override
    public void subUserStatus(User user) {
        if (user == null || user.getMobile() == null || "".equals(user.getMobile())) {
            throw new MyException(2001,"请求错误");
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",user.getMobile());
        User temp = userMapper.selectOne(wrapper);
        System.out.println(temp.getStatus() + " service  status=====================");
        if (temp == null) {
            throw new MyException(2001,"用户信息异常");
        }
        final Integer status = temp.getStatus();
        if (status <= 0) {
            throw new MyException(2001,"用户状态异常");
        }
        temp.setStatus(status-1);
        userMapper.updateById(temp);

    }

    @Override
    public List<Provice> getIpAdressNum() {
        List<Provice> provices = userMapper.selectIpAdress();
        return provices;
    }

}
